/**
 * @description 判断文件夹是否存在 如果不存在则创建文件夹
 */
const path = require('path');
const fs = require('fs');

function checkDirExist(dirname) {
  if (fs.existsSync(dirname)) {
    return true;
  } else {
    if (checkDirExist(path.dirname(dirname))) {
      fs.mkdirSync(dirname, 0777);
      return true;
    }
  }
}

//上传文件路径
function getUploadDirName() {
  const date = new Date();
  let year = date.getFullYear(),
    month = date.getMonth() + 1,
    day = date.getDate();
  const dir = `${year}/${month}/${day}`;
  // const dir = `${year}_${month}_${day}`;
  return dir;
}

// 哈希表
function createHash(hashLength) {
  // 默认长度 24
  // 0-9 a-z 共36个字型 
  return Array.from(Array(Number(hashLength) || 24), () => Math.floor(Math.random() * 36).toString(36)).join('');
}

//获取文件名
function getFileName(ext) {
  const date = new Date();
  const time = date.getTime();
  const dir = `${time}${createHash(6)}.${ext}`;
  return dir;
}

function getUploadFileExt(name) {
  let ext = name.split('.');
  return ext[ext.length - 1];
}

module.exports = {
  checkDirExist,
  getUploadDirName,
  getFileName,
  getUploadFileExt
};